package com.romotc.qqrobot.bean;

import java.util.List;

import com.romotc.joyin.bean.Customer;
import com.romotc.joyin.bean.CustomerGrantsService;
import com.romotc.joyin.bean.CustomerService;
import com.romotc.joyin.bean.MemberCustService;


/**
 * 虚拟账号/客服工号Service
 * @author Administrator
 *
 */
public class MemberCustServiceService {

	private static MemberCustService qryInstance = new MemberCustService();
	
	/**
	 * 根据Uid 客服工号查询客服对象
	 * @param id
	 * @param custServiceId
	 * @return
	 */
	public static MemberCustService qryMemberCustService(long robotUId,
			String custServiceId) {
		List<MemberCustService> custServ = (List<MemberCustService>)qryInstance
											.Filter("uid = " + robotUId + " and csId = " + custServiceId, 1, 1);
		if(custServ == null || custServ.isEmpty())
			return null;
		return custServ.get(0);
	}

	/**
	 * 根据id查询客服工号
	 * @param uin
	 * @return
	 */
	public static MemberCustService qryMemberCustServiceById(long id) {
		return qryInstance.Get(id);
	}

	/**
	 * 查询客户数量最少的客服人员
	 * @param uid 客服人员归属的机器人用户
	 * @return
	 */
	public static MemberCustService qryMinCustsService(long uid) {
		// 先根据UId查出来机器人用户下的客服人员
		List<MemberCustService> custServList = qryMemberCustServicesByUid(uid);
		
		//如果没有客服人员 返回空
		if(custServList == null || custServList.isEmpty())
			return null;
		
		int minGrantsSize = -1;
		MemberCustService minGrantSizeCustService = null;
		for(MemberCustService custService : custServList) {
			//逐个客服人员查grant表中的客户数量 
			int grantsSize = CustomerGrantsService.qryGrantsSize(custService.getId());
			
			//如果客户数量小于100直接返回这个客服人员 
			if(grantsSize < 100) {
				return custService;
			}

			
			//否则继续找  找到最小的一个
			if(grantsSize < minGrantsSize || minGrantsSize == -1) {
				minGrantsSize = grantsSize;
				minGrantSizeCustService = custService;
			}
			
		}
		
		return minGrantSizeCustService;
	}

	/**
	 * 根据UId查询其下的客服人员
	 * @param uid
	 * @return
	 */
	public static List<MemberCustService> qryMemberCustServicesByUid(long uid) {
		String filter = "uid = " + uid;
		
		int count = qryInstance.TotalCount(filter);
		List<MemberCustService> list = (List<MemberCustService>)qryInstance
			.FilterOrderBy(filter, "id ASC", 1, count);
		return list;
	}

	/**
	 * 查询
	 * @param uid2
	 * @param custQQ
	 * @return
	 */
	public static MemberCustService qryCustServiceByCustQNum(long uid2,
			String custQQ) {
		Customer cust = CustomerService.qryCustomerByQNum(uid2, custQQ);
		if(cust != null)
		{
			MemberCustService custService = qryInstance.Get(cust.getCsId());
			return custService;
		}
		return null;
	}
}
